package com.taotao.feign.proxy;

import com.taotao.feign.config.SWFeignConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author wangjin
 * @title: SwFeignInvocationHandler
 * @projectName sw-springcloud
 * @description:
 * @date 2021/11/21 15:49
 */
public class SwFeignInvocationHandler implements InvocationHandler, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //获取接口包的名称
        String pkName = method.getDeclaringClass().getPackage().getName();
        SWFeignConfig swFeignConfig = applicationContext.getBean("SWFeignConfig", SWFeignConfig.class);
        String serviceName = swFeignConfig.getFeignService().get(pkName);

        if (StringUtils.isEmpty(serviceName)) {
            throw new Exception("serviceName is null");
        }
        // 3.接口地址如何获取？
        GetMapping getMapping = method.getDeclaredAnnotation(GetMapping.class);
        if (getMapping == null) {
            throw new Exception("getMapping is null");
        }
        String[] requestName = getMapping.value();
        String requestUrl = "http://" + serviceName + requestName[0];
        RestTemplate restTemplate = applicationContext.getBean("restTemplate", RestTemplate.class);
        ResponseEntity<?> result = restTemplate.getForEntity(requestUrl, method.getReturnType());
        return result.getBody();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SwFeignInvocationHandler.applicationContext = applicationContext;
    }
}
